package com.mtw.bbs.common.jdbcBase.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.mtw.bbs.common.core.security.UserDetails;
import com.mtw.bbs.common.core.security.context.SecurityContextHolder;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;

import java.util.Date;


/**
 * mybatisPlus自动填充配置
 *
 */
@Configuration
public class AutoFillConfig implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {

        UserDetails details = SecurityContextHolder.getContext().getAuthentication();
        if (details != null){
            this.setFieldValByName("modifiedBy", details.getId(), metaObject);
            this.setFieldValByName("createdBy", details.getId(), metaObject);
        }
        this.setFieldValByName("createdDate", new Date(), metaObject);
        this.setFieldValByName("modifiedDate", new Date(), metaObject);
        this.setFieldValByName("deleted", 0, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        UserDetails details = SecurityContextHolder.getContext().getAuthentication();
        if (details != null){
            this.setFieldValByName("modifiedBy", details.getId(), metaObject);
        }
        this.setFieldValByName("modifiedDate", new Date(), metaObject);
    }
}
